package dao;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.*;
import java.util.List;

/**
 * BaseDao:数据库操作工具类
 * @author Administrator
 *
 */
public class BaseDao<T> {
	private static String driverClass="com.mysql.jdbc.Driver";
	private static String url="jdbc:mysql://localhost:3306/libsys?useUnicode=true&characterEncoding=utf-8";
	private static String userName="root";
	private static String password="123456";
	private Connection conn=null;
	private QueryRunner qr=null;
	private BasicRowProcessor processor=null;


	//获得连接
	public Connection getConnection(){
		try {
			//1、加载驱动
			Class.forName(driverClass);
			//2、获得连接
			conn=DriverManager.getConnection(url,userName,password);
			System.out.println("success");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	//关闭连接
	public void closeAll(Connection conn,Statement st,ResultSet rs){
		try {
			if(conn!=null)
				conn.close();
			if(st!=null)
				st.close();
			if(rs!=null)
				rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public BaseDao() {
		conn =getConnection(); //获取连接
		qr=new QueryRunner();//获取queryRunner对象
		processor =new BasicRowProcessor(new GenerousBeanProcessor());
	}

	/**
	 * 获取查询列表
	 * @param sql
	 * @param clazz 封装查询结果
 	 * @param params
	 * @return  list
	 * @throws SQLException
	 */
	public List<? extends Object> executeQuery(String sql, Object clazz, Object...params) throws SQLException {

		return (List<T>) qr.query(conn
				,sql
				,params
				,new BeanListHandler<>(clazz.getClass(),processor));
	}


	/**
	 * 查单个值  select count(*) from xxx
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public Object executeScalar(String sql,Object...params) throws SQLException {
		return qr.query(conn
						,sql
						,params
						,new ScalarHandler<>());
	}

	public int executeUpdate(String sql, Object...params) throws SQLException {
		conn =getConnection(); //获取连接
		QueryRunner qr=new QueryRunner();//获取queryRunner对象
		return qr.update(conn,sql,params);
	}

}
